package com.blyat.xsoft.kernel.component.pool;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.util.function.Supplier;

/**
 * @Auther: syh
 * @Date: 2020/8/3
 * @Description:
 */
public class ConnectionPooledObjectFactory<T extends Connection> extends BasePooledObjectFactory<T> {

    private final Supplier<T> connectionSupplier;

    public ConnectionPooledObjectFactory(Supplier<T> connectionSupplier) {
        this.connectionSupplier = connectionSupplier;
    }

    @Override
    public T create() throws Exception {
        return this.connectionSupplier.get();
    }

    @Override
    public PooledObject<T> wrap(T obj) {
        return new DefaultPooledObject<>(obj);
    }

    @Override
    public void destroyObject(PooledObject<T> p) throws Exception {
        p.getObject().close();
    }
}
